package tt.dz.mvc.controller.sys;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import tt.dz.entity.base.JsonCommon;
import tt.dz.entity.base.JsonForList;
import tt.dz.entity.base.OmsCommonParam;
import tt.dz.entity.base.OmsEntityEnum;
import tt.dz.entity.exception.OmsDaoException;
import tt.dz.entity.system.OmsOperList;
import tt.dz.entity.system.OmsRole;
import tt.dz.entity.system.OmsUrlTreeVO;
import tt.dz.mvc.controller.base.BaseAction;
import tt.dz.mvc.controller.base.BaseController;
import tt.dz.mvc.model.AddRoleModel;
import tt.dz.service.sys.RoleService;
import tt.dz.service.sys.UrlListService;
import tt.dz.util.ActionUtils;
import tt.dz.util.OmsConstant;

@Controller
@RequestMapping("roleApi")
public class RoleController extends BaseController
{
	private Log log = LogFactory.getLog(RoleController.class);

	@Autowired
	private RoleService roleServiceImpl;

	@Autowired
	private UrlListService urlListServiceImpl;

	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> add(@Valid AddRoleModel addRoleModel, HttpSession session) throws Exception
	{
		OmsRole role = addRoleModel.generateOmsRole();
		OmsOperList current_user = (OmsOperList) session.getAttribute(BaseAction.CommonParam.SESSION_USER);
		String newroleid = roleServiceImpl.add(role, current_user);
		return new JsonCommon<>(newroleid, OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> update(HttpServletRequest request, HttpServletResponse response)
	{
		OmsOperList user = this.getLoginUser(request);
		OmsRole role = genarateObj(request, user.getMs_manager_id(), false, false);
		//		String[] urlIds = request.getParameterValues("urlIds");
		//		role.setUrlIds(urlIds);
		return roleServiceImpl.update(role);
	}

	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> delete(HttpServletRequest request, HttpServletResponse response)
	{
		String role_id = request.getParameter("role_id");
		return roleServiceImpl.delete(role_id);
	}

	@RequestMapping(value = "findAllOrPage", method = RequestMethod.GET)
	@ResponseBody
	public JsonForList<?> findAllOrPage(HttpServletRequest request, HttpServletResponse response)
	{
		OmsRole role = genarateObj(request, getLoginUserId(request), false, true);
		return roleServiceImpl.findPageOrAll(this.buildQueryParam(request, true), role);
	}

	@RequestMapping(value = "findOwerRoles", method = RequestMethod.GET)
	@ResponseBody
	public JsonForList<?> findOwerRoles(HttpServletRequest request, HttpServletResponse response)
	{
		OmsOperList oper = this.getLoginUser(request);
		return roleServiceImpl.findRolesByEntityType(oper.getIsSupper() > 0 ? OmsEntityEnum.SUPER_OPERMERCHANT.getValue() : oper.getEntity_type());
	}

	@RequestMapping(value = "addUrlPower", method = RequestMethod.POST)
	@ResponseBody
	public JsonCommon<?> addUrlPower(HttpServletRequest request, HttpServletResponse response) throws OmsDaoException
	{
		String roleId = request.getParameter("roleId");
		//		String[] urlIds = request.getParameterValues("urlIds");
		String urlId_str = request.getParameter("urlIds");
		List<String> urlList = JSON.parseArray(urlId_str, String.class);
		String[] urlIds = (String[]) urlList.toArray(new String[0]);
		//		String[] urlIds = JSON.parseArray(urlId_str);
		return roleServiceImpl.addUrlPower(roleId, urlIds);
	}

	private OmsRole genarateObj(HttpServletRequest request, String userId, boolean isCreate, boolean isFind)
	{
		Map<String, String> params = ActionUtils.getParameterMap(request);
		return ActionUtils.getParamInstance(OmsRole.class, params, userId, isCreate, isFind);
	}

	private OmsOperList getLoginUser(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		return (OmsOperList) session.getAttribute(BaseAction.CommonParam.SESSION_USER);
	}

	private String getLoginUserId(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		return (String) session.getAttribute(BaseAction.CommonParam.SESSION_USERID);
	}

	private OmsCommonParam buildQueryParam(HttpServletRequest request, boolean isQueryTotal)
	{
		OmsCommonParam returnParam = new OmsCommonParam();
		returnParam.setQueryTotal(isQueryTotal);
		returnParam.setSortName(request.getParameter(BaseAction.CommonParam.SORT_NAME));
		String sortValue = request.getParameter(BaseAction.CommonParam.SORT_VALUE);
		String pageNo = request.getParameter(BaseAction.CommonParam.PAGE_NO);
		String pageSize = request.getParameter(BaseAction.CommonParam.PAGE_SIZE);
		if (StringUtils.isNumeric(sortValue))
		{
			returnParam.setSortValue(Integer.parseInt(sortValue));
		}

		if (StringUtils.isNumeric(pageNo) && StringUtils.isNumeric(pageSize))
		{
			returnParam.setPageNo(Integer.parseInt(pageNo));
			returnParam.setPageSize(Integer.parseInt(pageSize));
		}

		return returnParam;
	}

	@RequestMapping(value = "getAllUrlTree", method = RequestMethod.GET)
	@ResponseBody
	public JsonCommon<OmsUrlTreeVO> getAllUrlTree(String roleId)
	{
		OmsUrlTreeVO tree = urlListServiceImpl.getAllUrlTree(roleId);
		return new JsonCommon<>(tree, OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	@RequestMapping(value = "assignUrlToRole")
	@ResponseBody
	public JsonCommon assignUrlToRole(String root, String roleId, HttpSession session)
	{
		log.info(roleId);
		OmsUrlTreeVO rootvo = JSON.parseObject(root, OmsUrlTreeVO.class);
		log.info(rootvo);
		OmsOperList current_user = (OmsOperList) session.getAttribute(BaseAction.CommonParam.SESSION_USER);
		urlListServiceImpl.assignUrlToRole(rootvo, roleId, current_user.getOper_id());
		return new JsonCommon<>(OmsConstant.SuccessCodeEnum.SuccessCode.value(), OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}
}